﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace GetSmartIDEList.Lib.ORM
{
    /// <summary>
    /// 处理反射的类
    /// </summary>
    /// <typeparam name="T"> 与数据库表建立联系的类</typeparam>
    public class AttributesContext<T>
    {
        /// <summary>
        ///存放AttributesContext 类中所有的当前错误信息
        /// </summary>
        private string ExceptionBug;

        /// <summary>
        /// 读取映射的表名
        /// </summary>
        /// <param name="Info">自定义类型</param>
        /// <returns>放回建立映射表名 没简历表面返回空</returns>
        public string XTable(T info)
        {
            Type userAttu = info.GetType();
            try
            {
                TableAttribute tables = (TableAttribute)userAttu.GetCustomAttributes(false)[0];
                //在TableAttribute中我设置的是不容许多个特性所取 【0】
                return tables.TableName;
            }
            catch (ArgumentNullException e)
            {
                ExceptionBug = e.Message;
                return null;
            }
            catch (NotSupportedException e1)
            {
                ExceptionBug = e1.Message;
                return null;
            }
        }

        /// <summary>
        /// 放回自定义类与表建立的映射的字段名
        /// </summary>
        /// <param name="Info">与表建立映射联系的类</param>
        /// <returns>表字段的数组Dictionary   FieldAttribute ,Object[]| key 字段名 FieldAttribute ,value需要自己转换;
        /// object [2]  其中第一个是字段名称  第2个是字段值 </returns>
        public Dictionary<FieldAttribute, Object[]> XField(T info)
        {
            Dictionary<FieldAttribute, Object[]> xFields = new Dictionary<FieldAttribute, Object[]>();

            Type types = info.GetType();
            PropertyInfo[] typesPro = types.GetProperties();

            foreach (PropertyInfo pro in typesPro)
            {
                object[] attu = pro.GetCustomAttributes(false);

                object objValue = pro.GetGetMethod().Invoke(info, null);//取特性描述相应字段的值
                object objFieldName = (Object)pro.Name;//取特性对应类的字段名称
                object[] classInfo = new object[2];//把类中的字段名称与值存放；

                classInfo[0] = objFieldName;
                classInfo[1] = objValue;

                foreach (Attribute afield in attu)
                {
                    if (afield is FieldAttribute)
                    {
                        FieldAttribute column = afield as FieldAttribute;//把afield转换成FieldAttribute类型
                        xFields.Add(column, classInfo);//把字段存放到key 把特性描述的字段字存放到value
                    }

                }
            }
            return xFields;
        }
    }
}
